package com.sinosoft.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.sinosoft.enums.http.StatusCode;
import com.sinosoft.feign.oauth2.OauthFeign;
import com.sinosoft.utils.string.StringUtils;
import com.sinosoft.vo.http.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/** token 校验  通过配置的resourceId与oauth2表中的resourceIds字段进行匹配，当没有配置resourceId时默认匹配所有
 * @Auther: zouren
 * @Date: 2019/2/27 09:00
 * @Description:
 */
@Component
public class TokenValidateGatewayFilterFactory extends AbstractGatewayFilterFactory<TokenValidateGatewayFilterFactory.Config> {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private OauthFeign oauthfeign;
    public  TokenValidateGatewayFilterFactory(){
        super(Config.class);
    }
//    @Autowired
//    private GProperties routeproperties;
    private AntPathMatcher ant = new AntPathMatcher();
    @Override
    public GatewayFilter apply(Config config) {
        return  (exchange, chain) ->{
            
            

            //test!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            if(exchange.getAttributes().containsKey("IgnoredGlobalFilter") && "@actuator".equalsIgnoreCase((String)exchange.getAttributes().get("IgnoredGlobalFilter"))) {
                return chain.filter(exchange);
            }
            //test!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            
            String token = getToken(exchange);
            //如果没带令牌, 返回no token provided
            if (StringUtils.isBlank(token)) {
                logger.error("No Token !!" + exchange.getRequest().getRemoteAddress().getAddress() + "   !!" + exchange.getRequest().getURI());
                return getServerHttpResponse(exchange,StatusCode.UNAUTHORIZED,"no token provided" );
            }
            JSONObject user = oauthfeign.oauth2user(token);
            //令牌不合法
            if (user.containsKey("code") && user.containsKey("msg")) {
                return getServerHttpResponse(exchange, StatusCode.getByCode(user.getString("code")), user.getString("description"));
            }

            //如果localhost:8043/user调通了，　看看那些接口对这个token开放
            if (user.containsKey("details") && user.containsKey("oauth2Request")) {
                //如果请求的接口在token授权范围内，放行
                if (checkResourceId(config, user)) {
                    //logger.info("Access Granted   @@" + exchange.getRequest().getRemoteAddress().getAddress() + "   @@" + exchange.getRequest().getURI());
                    return chain.filter(exchange);
                } else {
                    //如果请求的接口不在token授权范围内，返回权限不够
                    return  getServerHttpResponse(exchange,StatusCode.UNAUTHORIZED," sorry your token cannot perform this action" );
                }
            }

            return null ;
        };
    }

    /**
     * 返回错信息
     * @param exchange
     * @param statusCode
     * @param description
     * @return
     */
    private Mono<Void> getServerHttpResponse( ServerWebExchange exchange,StatusCode statusCode,String  description ){
        Result result = Result.failure(statusCode);
        result.setDescription(description);
        result.setPath(exchange.getRequest().getURI().getPath());
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(statusCode.getHttpStatus());
        //设置headers
        HttpHeaders httpHeaders = response.getHeaders();
        httpHeaders.add("Content-Type", MediaType.APPLICATION_JSON_UTF8.toString());
        httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
        //设置body
        DataBuffer bodyDataBuffer = response.bufferFactory().wrap(result.toJSONString().getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(bodyDataBuffer));
    }

    /**
     * 得到令牌
     * @param exchange
     * @return
     */
    private String getToken(ServerWebExchange exchange){
        String token  = exchange.getRequest().getQueryParams().getFirst("access_token");

        if(StringUtils.isBlank(token)){
            token =  exchange.getRequest().getHeaders().getFirst("Authorization");
        }
        return token;
    }

    /**
     * 校验资源
     * @param config
     * @param user
     * @return
     */
    public boolean checkResourceId(Config config, JSONObject user) {
        logger.info("checkResourceId");
        List<String> resourceIds = user.getJSONObject("oauth2Request").getJSONArray("resourceIds").toJavaList(String.class);
        boolean flag = true;
       if(resourceIds!=null&&resourceIds.size()>=1){
           flag = resourceIds.stream().anyMatch(e->ant.match(config.getResourceId(),e));
       }

        return flag;
    }

    public static class Config {
        private   String resourceId;

        public String getResourceId() {
            if( StringUtils.isBlank(resourceId)){
                resourceId="*";
            }
            return resourceId;
        }

        public void setResourceId(String resourceId) {
            this.resourceId = resourceId;
        }
    }

}



